#coding:utf-8
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render
from models import node_info
from django.contrib.auth.decorators import login_required
from forms import AddForm
import urllib2
import json

@login_required(login_url="/login/")
def index(request):
    return render(request, 'index.html')

@login_required(login_url="/login/")
def node_view(request):
    if request.method == 'POST':# 当提交表单时

        form_info = AddForm(request.POST) # form 包含提交的数据

        if form_info.is_valid():# 如果提交的数据合法
            #form = form_info.cleaned_data
            form_info.save()
            return HttpResponseRedirect('/node')
        else:
            return HttpResponse(json.dumps({"success":True}), content_type="application/json") #这里看下怎么抛错#http://stackoverflow.com/questions/27481308/django-bootstrap-modal-after-form-submission

    else:# 当正常访问时
        form_info = AddForm()
    node_list = node_info.objects.all()
    return render(request, 'node_view.html',locals())

@login_required(login_url="/login/")
def nodestatus(request,id=7):
    i = node_info.objects.get(id=id)
    rlist = []
    rlist.append({"data":{"NodeIP":i.NodeIP,"node_name":i.node_name,"Status":i.Status,"cpu_free":i.cpu_free,"recv_rate0":i.recv_rate0}})
    rjson = json.dumps(rlist)
    response = HttpResponse()
    response['Content-Type'] = "text/javascript"
    response.write(rjson)
    return response

@login_required(login_url="/login/")
def node_detail(request,node_id):
    try:
        num = int(node_id)
    except ValueError:
        raise Http404
    node = node_info.objects.get(id=num)
    ip = node.NodeIP
    token = node.token
    try:
        jsonres = urllib2.urlopen('http://%s:3000/ocdn/status?token=%s'%(ip,token),timeout=2).read()
    except:
        jsonres = False
        tmp = {}
        tmp['result'] = False
    if jsonres:
        tmp = json.loads(jsonres)
        print jsonres
    if tmp['result']:
        node.Status = "online"
        node.Mem_per = tmp['data']['memory']['mem']['per']
        node.Mem_used = tmp['data']['memory']['mem']['used']
        node.Mem_total = tmp['data']['memory']['mem']['total']
        node.cpu_free = tmp['data']['cpu']['status']
        network = tmp['data']['network']
        node.System_release = tmp['data']['system']
        node.Kernel_release = tmp['data']['kernel']
        #network = {}
        ##for k,v in tmp['data']['network']:
        #   netowrk = {k:{'transmit_bytes_speed':v['count']['transmit-bytes-speed']}}

    else:
        node.Status = "offline"
    return render(request, 'node_detail.html',locals())


@login_required(login_url="/login/")
def node_del(request,node_id):
    try:
        num = int(node_id)
    except ValueError:
        raise Http404
    node = node_info.objects.get(id=num)
    node.delete()
    return HttpResponseRedirect('/node/')

@login_required(login_url="/login/")
def node_mod(request,node_id):
    try:
        num = int(node_id)
    except ValueError:
        raise Http404
    if request.method == 'POST':# 当提交表单时
        node = node_info.objects.get(id=node_id) # form 包含提交的数据
        form = AddForm(request.POST,instance=node)
        if form.is_valid():# 如果提交的数据合法
            #form = form_info.cleaned_data
            form.save()
            return HttpResponseRedirect('/node')
        #else:
        #    return render(request, 'node_view.html',locals()) #这里看下怎么抛错
    else:
        node = node_info.objects.get(id=node_id)
        form = AddForm(
            initial={'node_name':node.node_name,'NodeIP':node.NodeIP,'token':node.token,'nodegroup':node.nodegroup,'route':node.route}
        )
    return render(request, 'node_modify.html',locals())

